package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.ComplaintTypeEnum;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.enums.SourceTypeEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceKeyVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceQueryVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.common.vo.individuation.JzzSaveVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduLivePlaceIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 居住证表业务实现类
 *
 * @author wangtao
 * @since 2022-12-28
 */
@ApiService(funcCode = "EduLivePlace", title = "居住证表")
public class EduLivePlaceIntegrationImpl implements EduLivePlaceIntegration {

    @Autowired
    public EduLivePlaceService eduLivePlaceService;
    @Autowired
    public DictIntegration dictIntegration;
    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    public EduSchoolService eduSchoolService;
    @Autowired
    public OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduComplaintService eduComplaintService;
    @Autowired
    private CommonIntegration commonIntegration;
    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private  EduhLivePlaceService eduhLivePlaceService;
    @Autowired
    private  EduDataTaskDetailService eduDataTaskDetailService;
    @Autowired
    private EduLivePlaceOfflineService eduLivePlaceOfflineService;



    public static final String APP_JZZ_LIMIT = "APP_JZZ_LIMIT_";
    public static final String get_jzz = "APP_JZZ_IDCARD_";

    public static final String handleTable = "edu_live_place";

    @Override
    @OpApi(funcCode = "EduLivePlace0001", title = "居住证表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduLivePlaceVO> getList(EduLivePlaceQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (CollectionUtils.isEmpty(areaCodeList)){
            throw new AppException("必须传入行政区划");
        }
        Integer year = eduHelper.thisYear();
        if (ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(year);
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null){
            desensitizeFlag = true;
        }
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        if (queryHistoryFlag){
            QueryWrapper<EduhLivePlace> hLivePlaceQueryWrapper = new QueryWrapper<>();
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), handleTable);
            if (encryptFlag){
                //查询条件加密
                eduLivePlaceService.queryEncrypt(vo);
            }
            hLivePlaceQueryWrapper
                    .lambda()
                    .in(EduhLivePlace::getAreaCode, areaCodeList)
                    .eq(!ObjectUtils.isEmpty(vo.getSfzh()), EduhLivePlace::getSfzh, vo.getSfzh())
                    .like(!ObjectUtils.isEmpty(vo.getXm()), EduhLivePlace::getXm, vo.getXm( ))
                    .eq(!ObjectUtils.isEmpty(vo.getYear()), EduhLivePlace::getYear, vo.getYear())
                    .eq(!ObjectUtils.isEmpty(vo.getSourceType()), EduhLivePlace::getSourceType, vo.getSourceType())
                    .like(!ObjectUtils.isEmpty(vo.getJzdz()), EduhLivePlace::getJzdz, vo.getJzdz());
            PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
            List<EduhLivePlace> hLivePlaceList = eduhLivePlaceService.list(hLivePlaceQueryWrapper);
            if (CollectionUtils.isEmpty(hLivePlaceList)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduLivePlaceVO> resultList = new ArrayList<>();
            for (EduhLivePlace eduhLivePlace : hLivePlaceList) {
                //对字段进行解密
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhLivePlace.getEncryptFlag())){
                    eduhLivePlaceService.decrypt(eduhLivePlace);
                }
                //判断是否脱敏
                if (desensitizeFlag){
                    eduhLivePlace.setXm(EduDesensitizeUtil.desensitizeFullName(eduhLivePlace.getXm()));
                    eduhLivePlace.setSfzh(EduDesensitizeUtil.desensitizeIdcard(eduhLivePlace.getSfzh()));
                    eduhLivePlace.setJzdz(EduDesensitizeUtil.desensitizeAddress(eduhLivePlace.getJzdz()));
                }
                EduLivePlaceVO placeVO = Convert.convert(EduLivePlaceVO.class, eduhLivePlace);
                resultList.add(placeVO);
            }
            // 不为空则获取分页结果
            PageInfo<EduhLivePlace> pageInfo = new PageInfo<>(hLivePlaceList);
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }else{
            QueryWrapper<EduLivePlace> livePlaceWrapper = new QueryWrapper<>();
            livePlaceWrapper
                    .lambda()
                    .in(EduLivePlace::getAreaCode,areaCodeList)
                    .eq(!ObjectUtils.isEmpty(vo.getSfzh()), EduLivePlace::getSfzh, vo.getSfzh())
                    .like(!ObjectUtils.isEmpty(vo.getXm()), EduLivePlace::getXm, vo.getXm())
                    .eq(!ObjectUtils.isEmpty(vo.getYear()), EduLivePlace::getYear, vo.getYear())
                    .eq(!ObjectUtils.isEmpty(vo.getSourceType()), EduLivePlace::getSourceType, vo.getSourceType())
                    .like(!ObjectUtils.isEmpty(vo.getJzdz()), EduLivePlace::getJzdz, vo.getJzdz());
            PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
            List<EduLivePlace> list = eduLivePlaceService.list(livePlaceWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduLivePlace> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduLivePlaceVO> resultList = Convert.toList(EduLivePlaceVO.class, pageInfo.getList());
            // 转义数据字典值
            // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
            //脱敏 姓名身份证
            if (desensitizeFlag){
                for (EduLivePlaceVO eduLivePlaceVO : resultList) {
                    eduLivePlaceVO.setXm(EduDesensitizeUtil.desensitizeFullName(eduLivePlaceVO.getXm()));
                    eduLivePlaceVO.setSfzh(EduDesensitizeUtil.desensitizeIdcard(eduLivePlaceVO.getSfzh()));
                    eduLivePlaceVO.setJzdz(EduDesensitizeUtil.desensitizeAddress(eduLivePlaceVO.getJzdz()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0002", title = "居住证表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduLivePlaceVO getById(EduLivePlaceKeyVO vo) {
        EduLivePlace entity = eduLivePlaceService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(entity)) {
            //在线表查不到，去查一遍历史表
            EduhLivePlace livePlace = eduhLivePlaceService.getById(vo.getLivePlaceId());
            if (ObjectUtils.isEmpty(livePlace)){
                throw new AppException("查询不到详细信息!");
            }
            //查出历史表数据,根据数据加密状态判断是否加密过
            //对字段进行解密
            if (BoolEnum.TRUE.getType().equalsIgnoreCase(livePlace.getEncryptFlag())){
                eduhLivePlaceService.decrypt(livePlace);
            }
            EduLivePlaceVO result = Convert.convert(EduLivePlaceVO.class, livePlace);
            return result;
        }
        EduLivePlaceVO result = Convert.convert(EduLivePlaceVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "EduLivePlace0003", title = "居住证表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduLivePlaceVO vo) {
        //获取招生年度
        OperationCurVO byvoyear = new OperationCurVO();
        EduOperationCacheDetailVO getyearvo = new EduOperationCacheDetailVO();
        getyearvo = operationCacheIntegration.getPeriodYear(byvoyear);
        Boolean enrollFlag= this.checkEnroll(vo.getSfzh(),eduHelper.thisYear());
        if(enrollFlag){
            throw new AppException("已存在报名数据，不能登记!");
        }


        //主键为空为新增校验；同一个身份证，同一个年度不能维护多条数据
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            QueryWrapper<EduLivePlace> livePlaceWrapper = new QueryWrapper<>();
            livePlaceWrapper.lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getSfzh()), EduLivePlace::getSfzh, vo.getSfzh())
                    .eq(!ObjectUtils.isEmpty(vo.getZjztdm()), EduLivePlace::getZjztdm,vo.getZjztdm())
                    .eq(!ObjectUtils.isEmpty(vo.getYear()), EduLivePlace::getYear, vo.getYear());
            if(eduLivePlaceService.count(livePlaceWrapper)>0){
                throw new AppException("同一个身份证，同一年度不能维护多条数据!");
            }
            if(!vo.getYear().equals(getyearvo.getYear())){
                throw new AppException("只能新增招生当前年度的数据!");
            }

        }else{
            //主键不为空为修改校验
            EduLivePlaceKeyVO editvo = new EduLivePlaceKeyVO();
            editvo.setLivePlaceId(vo.getLivePlaceId());
            EduLivePlaceVO revo = new EduLivePlaceVO();
            revo = getById(editvo);
            if(!revo.getYear().equals(getyearvo.getYear())){
                throw new AppException("只能修改招生当前年度的数据!");
            }

        }

        //校验身份证格式
        if (!IdcardUtil.isValidCard(vo.getSfzh())) {
            throw new AppException("请输入正确的身份证格式！");
        }

    }


    public Boolean checkEnroll(String idcard, Integer year) {
        if(year==null){
            EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
            year=eduOperationCacheDetailVO.getYear();
        }
        List<String> enrollStatusList=new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard,idcard)
                .eq(EduStudentEnroll::getYear,year)
                .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
        if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
            return false;
        }
        return true;
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0004", title = "居住证表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "EduLivePlace0004",
            operationName = "居住证表新增",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLivePlaceVO add(EduLivePlaceVO vo) {
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        if(StringUtils.isBlank(vo.getXzqhdm())){
            vo.setXzqhdm(vo.getAreaCode());
        }
        if (!ObjectUtils.isEmpty(vo.getMzdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("NATION");
            dictvo.setDictKey(vo.getMzdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setMz(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getXbdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("SEX");
            dictvo.setDictKey(vo.getXbdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setXb(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getZjztdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("ZJZT");
            dictvo.setDictKey(vo.getZjztdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setZjzt(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getZxyydm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("ZXYY");
            dictvo.setDictKey(vo.getZxyydm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setZxyy(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getHksxdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("AREA");
            dictvo.setDictKey(vo.getHksxdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setHksx(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getXzqhdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("STREET");
            dictvo.setDictKey(vo.getXzqhdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setXzqhmc(dictvalue);
        }
        //获取数据来源
        String orgid = SessionUtil.getOrgId();
        //根据组织编码判断数据来源是否是学校录入
        LambdaQueryWrapper<EduSchool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSchool::getDel,0);
        queryWrapper.eq(EduSchool::getOrgId,orgid);
        if(eduSchoolService.count(queryWrapper)==0){
            vo.setSourceType(SourceTypeEnum.admin.getType());
        }else{
            vo.setSourceType(SourceTypeEnum.school.getType());
        }

        //保存前校验
        checkSave(vo);
        //保存数据
        EduLivePlace entity = Convert.convert(EduLivePlace.class, vo);
        eduLivePlaceService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setLivePlaceId(entity.getLivePlaceId());
        clearCache(entity.getSfzh());
        return vo;
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0005", title = "居住证表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "EduLivePlace0005",
            operationName = "居住证表修改",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLivePlaceVO edit(EduLivePlaceVO vo) {
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        if (queryHistoryFlag){
            throw new AppException("历史数据不允许修改!");
        }
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduLivePlace oldEntity = eduLivePlaceService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        if (!ObjectUtils.isEmpty(vo.getMzdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("NATION");
            dictvo.setDictKey(vo.getMzdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setMz(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getXbdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("SEX");
            dictvo.setDictKey(vo.getXbdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setXb(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getZjztdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("ZJZT");
            dictvo.setDictKey(vo.getZjztdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setZjzt(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getZxyydm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("ZXYY");
            dictvo.setDictKey(vo.getZxyydm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setZxyy(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getHksxdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("AREA");
            dictvo.setDictKey(vo.getHksxdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setHksx(dictvalue);
        }
        if (!ObjectUtils.isEmpty(vo.getXzqhdm())) {
            DictQueryVO dictvo = new DictQueryVO();
            dictvo.setDictField("STREET");
            dictvo.setDictKey(vo.getXzqhdm());
            String dictvalue = dictIntegration.getValue(dictvo);
            vo.setXzqhmc(dictvalue);
        }

        //保存前校验
        checkSave(vo);
        String orgid = SessionUtil.getOrgId();
        LambdaQueryWrapper<EduSchool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSchool::getDel, 0);
        queryWrapper.eq(EduSchool::getOrgId, orgid);
        if (eduSchoolService.count(queryWrapper) == 0) {
            vo.setSourceType(SourceTypeEnum.admin.getType());
        } else {
            vo.setSourceType(SourceTypeEnum.admin.getType());
        }
        //保存数据
        EduLivePlace entity = Convert.convert(EduLivePlace.class, vo);
        entity.setUpdateName(SessionUtil.getUserId());
        entity.setUpdateTime(new Date());//取当前时间为修改时间
        eduLivePlaceService.updateById(entity);
        clearCache(entity.getSfzh());
        return vo;
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0006", title = "居住证表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "EduLivePlace0006",
            operationName = "居住证表删除",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduLivePlaceKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduLivePlace entity = eduLivePlaceService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        //获取招生年度
        OperationCurVO byvoyear = new OperationCurVO();
        EduOperationCacheDetailVO getyearvo = new EduOperationCacheDetailVO();
        getyearvo = operationCacheIntegration.getPeriodYear(byvoyear);
        EduLivePlaceVO revo = new EduLivePlaceVO();
        revo = getById(vo);
        if(!revo.getYear().equals(getyearvo.getYear())){
            throw new AppException("只能删除招生当前年度的数据!");
        }
        eduLivePlaceService.removeById(vo.getLivePlaceId());
        clearCache(entity.getSfzh());
    }

    //清除缓存
    private void clearCache(String idcard){
        //查询人员
        if(StringUtils.isBlank(idcard)){
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            //居住证
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
    @Override
    @OpApi(funcCode = "EduLivePlace0007", title = "根据身份证获取居住证信息并保存", funcType = FuncTypeEnum.query)
    public List<EduLivePlaceVO> getLivePlaceAndSave(JzzSaveVO vo) {
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        ApiModel apiModel=eduHelper.getEduFunc("saveJzzInterfaceData",vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduLivePlaceVO> list= (List<EduLivePlaceVO>) apiModel.getMethod().invoke(bean, vo);
                if(!CollectionUtils.isEmpty(list)){

                    return list;
                }
            }else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }
        return new ArrayList<>();
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0008", title = "家长端获取居住证信息并保存", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduLivePlaceVO> getAppLivePlaceAndSave(JzzSaveVO vo) {
        String idcard=vo.getIdcard();
        boolean flag=false;
        if(StringUtils.isBlank(idcard)){
            idcard=SessionUtil.getSessionInfo().getIdcard();
            flag=true;
        }

        //同一身份证一天最多同步获取3次
        String key = get_jzz+idcard;
        Integer getCount= (Integer) redisHelper.get(key);
        if(getCount==null||getCount==0){
            getCount=1;
        }else{
            getCount=getCount+1;
        }
        redisHelper.set(key,getCount,43200);
        if(getCount>3){
            throw new AppException("24小时内最多获取三次，如还有问题，请致电联系");
        }
        Object maxObj = redisHelper.get(APP_JZZ_LIMIT + DateUtil.today());
        int max;
        if (org.springframework.util.ObjectUtils.isEmpty(maxObj)) {
            redisHelper.set(APP_JZZ_LIMIT + DateUtil.today(), 1);
            max = 1;
        } else {
            max = (int) redisHelper.get(APP_JZZ_LIMIT + DateUtil.today());
            max++;
            redisHelper.set(APP_JZZ_LIMIT + DateUtil.today(), max);
        }
        CommonVO commonVO=new CommonVO();
        commonVO.setParamKey("APP_JZZ_LIMIT");
        String limit = commonIntegration.getValueByKey(commonVO);
        if (!org.springframework.util.ObjectUtils.isEmpty(limit) && max > Integer.parseInt(limit)) {
            throw new AppException("今日大数据接口已达上限，请明日再试！");
        }
        List<EduLivePlaceVO> retList=new ArrayList<>();
        Integer year = operationCacheIntegration.getPeriodYear().getYear();
        final String finalId=idcard;
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda().select(EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFullName,
                EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getFatherName,
                EduStudentEnrollPre::getMotherName,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, finalId)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, finalId)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, finalId);
                        }).orderByAsc(EduStudentEnrollPre::getIdcard);
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);
        if(flag){
            if(CollectionUtils.isEmpty(queryList)){
                return new ArrayList<>();
            }
            List<String> idcardList=new ArrayList<>();
            for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
                Boolean enrollFlag= this.checkEnroll(eduStudentEnrollPre.getIdcard(),year);
                if(enrollFlag){
                    throw new AppException("已存在报名数据，不能重新获取数据!");
                }
            }
            for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
                if(StringUtils.isNotBlank(eduStudentEnrollPre.getIdcard())&&!idcardList.contains(eduStudentEnrollPre.getIdcard())){

                    idcardList.add(eduStudentEnrollPre.getIdcard());
                    JzzSaveVO saveVO=new JzzSaveVO();
                    saveVO.setIdcard(eduStudentEnrollPre.getIdcard());
                    saveVO.setName(eduStudentEnrollPre.getFullName());
                    saveVO.setReplaceFlag(true);
                    saveVO.setLocalFlag(vo.getLocalFlag());
                    saveVO.setReqIp(vo.getReqIp());
                    retList.addAll(getLivePlaceAndSave(saveVO));
                }
                if(StringUtils.isNotBlank(eduStudentEnrollPre.getFatherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getFatherIdcard())){
                    idcardList.add(eduStudentEnrollPre.getFatherIdcard());
                    JzzSaveVO saveVO=new JzzSaveVO();
                    saveVO.setIdcard(eduStudentEnrollPre.getFatherIdcard());
                    saveVO.setName(eduStudentEnrollPre.getFatherName());
                    saveVO.setReplaceFlag(true);
                    saveVO.setLocalFlag(vo.getLocalFlag());
                    saveVO.setReqIp(vo.getReqIp());
                    retList.addAll(getLivePlaceAndSave(saveVO));
                }
                if(StringUtils.isNotBlank(eduStudentEnrollPre.getMotherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getMotherIdcard())){
                    idcardList.add(eduStudentEnrollPre.getMotherIdcard());
                    JzzSaveVO saveVO=new JzzSaveVO();
                    saveVO.setIdcard(eduStudentEnrollPre.getMotherIdcard());
                    saveVO.setName(eduStudentEnrollPre.getMotherName());
                    saveVO.setReplaceFlag(true);
                    saveVO.setLocalFlag(vo.getLocalFlag());
                    saveVO.setReqIp(vo.getReqIp());
                    retList.addAll(getLivePlaceAndSave(saveVO));
                }
            }
        }else{
            JzzSaveVO saveVO=new JzzSaveVO();
            saveVO.setIdcard(vo.getIdcard());
            saveVO.setName(vo.getName());
            saveVO.setReplaceFlag(true);
            saveVO.setLocalFlag(vo.getLocalFlag());
            saveVO.setReqIp(vo.getReqIp());
            retList.addAll(getLivePlaceAndSave(saveVO));
        }
        if(!CollectionUtils.isEmpty(queryList)){
            for(EduStudentEnrollPre pre:queryList) {
                if (StringUtils.isNotBlank(pre.getIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
                }
                if (StringUtils.isNotBlank(pre.getFatherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getFatherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
                }
                if (StringUtils.isNotBlank(pre.getMotherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getMotherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
                }
                eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());

            }
        }
        return retList;
    }

    @Override
    @OpApi(funcCode = "EduLivePlace0009", title = "家长端当年适龄子女获取我的居住证", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduLivePlaceVO> getAppLivePlaceList(AreaControlVO vo) {
        String idcard=SessionUtil.getSessionInfo().getIdcard();
        if(StringUtils.isBlank(idcard)){
            throw new AppException("用户的证件号码不能为空");
        }
        String key=idcard;
        Cache<String, List<EduLivePlaceVO>> cache = JetCacheUtils.create(EduCache.EDU_MY_ENROLL_PRE_JZZ, CacheType.BOTH, Duration.ofHours(6), Duration.ofSeconds(20));
        List<EduLivePlaceVO> value=  cache.get(key);
        if(value!=null){
            return value;
        }
        List<String> areaCodeList = new ArrayList<>();
        //如果行政区划为空，就去系统配置的统筹区编码
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        //根据配置的行政区划，
        List<SelectVO> selectList = dictIntegration.getDistrictByOrg(new DictAreaVO());

        if (!CollectionUtils.isEmpty(selectList)){
            areaCodeList = selectList.stream().map(SelectVO::getDictKey).collect(Collectors.toList());
        }else{
            areaCodeList.add(vo.getAreaCode());
        }
        //获取居住证有效截止日期
        EduOperationCacheQueryVO queryOpVO=new EduOperationCacheQueryVO();
        queryOpVO.setOperating("YW051");
        queryOpVO.setAreaCode(vo.getAreaCode());
        queryOpVO.setClassify("2");
        EduOperationCacheDetailVO jzzOption=eduSystemConfigIntegration.getEduOperationOne(queryOpVO);
        Integer endTime=0;
        int year = jzzOption != null ? jzzOption.getYear() : eduHelper.thisYear();
        if(jzzOption!=null&&jzzOption.getEndTime()!=null){
            endTime=Integer.parseInt(DateUtil.format(jzzOption.getEndTime(),"YYYYMMDD"));
        }

        //去查询预采集信息，根据登录人身份证去预采集表比对父母学生身份证
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda()
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                        }).orderByAsc(EduStudentEnrollPre::getIdcard);
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);
        if(CollectionUtils.isEmpty(queryList)){
            return new ArrayList<>();
        }
        //取出父母和学生身份信息
        List<String> idcardList=new ArrayList<>();
        for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
            if(StringUtils.isNotBlank(eduStudentEnrollPre.getIdcard())&&!idcardList.contains(eduStudentEnrollPre.getIdcard())){
                idcardList.add(eduStudentEnrollPre.getIdcard());
            }
            if(StringUtils.isNotBlank(eduStudentEnrollPre.getFatherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getFatherIdcard())){
                idcardList.add(eduStudentEnrollPre.getFatherIdcard());
            }
            if(StringUtils.isNotBlank(eduStudentEnrollPre.getMotherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getMotherIdcard())){
                idcardList.add(eduStudentEnrollPre.getMotherIdcard());
            }
        }

        QueryWrapper<EduLivePlaceOffline> offlineQueryWrapper=new QueryWrapper<>();
        offlineQueryWrapper.lambda().select(EduLivePlaceOffline::getLivePlaceId,EduLivePlaceOffline::getSfzh,EduLivePlaceOffline::getAuthStatus,EduLivePlaceOffline::getXm,EduLivePlaceOffline::getQzrq,EduLivePlaceOffline::getQzdqrq,EduLivePlaceOffline::getJzdz,EduLivePlaceOffline::getZjzt)
                .eq(EduLivePlaceOffline::getYear,year)
                .in(EduLivePlaceOffline::getSfzh,idcardList)
                .ne(EduLivePlaceOffline::getAuthStatus, AuthStatusEnum.YES.getType()).orderByDesc(EduLivePlaceOffline::getCreateTime);
        List<EduLivePlaceOffline> offlineList=eduLivePlaceOfflineService.list(offlineQueryWrapper);
        //去查询居住证信息
        QueryWrapper<EduLivePlace> livePlaceQueryWrapper = new QueryWrapper<>();
        livePlaceQueryWrapper.lambda().eq(EduLivePlace::getYear, year)
                .in(EduLivePlace::getXzqhdm,areaCodeList)
                .in(EduLivePlace::getSfzh, idcardList).orderByAsc(EduLivePlace::getSfzh);
        List<EduLivePlace> livePlaceList = eduLivePlaceService.list(livePlaceQueryWrapper);
        if (!CollectionUtils.isEmpty(livePlaceList)) {
            String today=DateUtil.today().replaceAll("-","");
            List<EduLivePlaceVO> livePlaceVOList = new ArrayList<>();
            for(EduLivePlace eduLivePlace:livePlaceList) {
                EduLivePlaceVO eduLivePlaceVO = Convert.convert(EduLivePlaceVO.class, eduLivePlace);
                QueryWrapper<EduComplaint> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().select(EduComplaint::getHandleStatus).eq(EduComplaint::getType, ComplaintTypeEnum.sb.getType())
                        .eq(EduComplaint::getHandleStatus,BoolEnum.FALSE.getType())
                        .eq(EduComplaint::getOtherId,eduLivePlace.getLivePlaceId());
                List<EduComplaint> complaints=eduComplaintService.list(queryWrapper);
                if(!CollectionUtils.isEmpty(complaints)){
                    eduLivePlaceVO.setJzzHandleStatus(complaints.get(0).getHandleStatus());
                }
                eduLivePlaceVO.setExpireFlag(true);
                if(StringUtils.isNotBlank(eduLivePlaceVO.getQzdqrq())&&endTime!=0){
                    if("2".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"3".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"5".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"正常".equals(eduLivePlaceVO.getZjzt())){
                        //到期时间小于截止的，设置为终止
                        Integer qzdqrq = Integer.parseInt(eduLivePlaceVO.getQzdqrq().replaceAll("-", "").replaceAll("/", ""));
                        if (qzdqrq <= endTime) {
                            if (qzdqrq < Integer.parseInt(today)) {
                                eduLivePlaceVO.setZjztdm("5");
                                eduLivePlaceVO.setZjzt("中止");
                            }
                        }else{
                            eduLivePlaceVO.setZjztdm("2");
                            eduLivePlaceVO.setZjzt("正常");
                            if(StringUtils.isNotBlank(eduLivePlaceVO.getQzrq())){
                                if(Integer.parseInt(eduLivePlaceVO.getQzrq().replaceAll("-","").replaceAll("/",""))>endTime){
                                    eduLivePlaceVO.setZjztdm("5");
                                    eduLivePlaceVO.setZjzt("无效");
                                }
                            }

                        }
                    }
                    if(("2".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"3".equalsIgnoreCase(eduLivePlaceVO.getZjztdm()))){
                        //正常和待签注处理
                        if(Integer.parseInt(eduLivePlaceVO.getQzdqrq().replaceAll("-","").replaceAll("/",""))<=endTime&&Integer.parseInt(today)<endTime){
                            eduLivePlaceVO.setExpireFlag(true);
                        }else{
                            eduLivePlaceVO.setExpireFlag(false);
                        }
                    }
                }else{
                    if("正常".equalsIgnoreCase(eduLivePlaceVO.getZjzt())){
                        eduLivePlaceVO.setExpireFlag(false);
                        eduLivePlaceVO.setZjztdm("2");
                    }else{
                        eduLivePlaceVO.setExpireFlag(true);
                    }
                }

                livePlaceVOList.add(eduLivePlaceVO);
            }
            if (!CollectionUtils.isEmpty(offlineList)) {
                for (EduLivePlaceOffline eduLivePlaceOffline : offlineList) {
                    if (AuthStatusEnum.NODO.getType().equals(eduLivePlaceOffline.getAuthStatus())) {
                        boolean addFlag = true;
                        for (EduLivePlaceVO livePlaceVO : livePlaceVOList) {
                            if (eduLivePlaceOffline.getSfzh().equals(livePlaceVO.getSfzh())) {
                                addFlag = false;
                                livePlaceVO.setAuthStatus(AuthStatusEnum.NODO.getType());
                                livePlaceVO.setAuthStatusName("待审核");
                            }
                        }
                        if (addFlag) {
                            EduLivePlaceVO placeVO = Convert.convert(EduLivePlaceVO.class, eduLivePlaceOffline);
                            placeVO.setAuthStatusName("待审核");
                            livePlaceVOList.add(placeVO);
                        }

                    } else {
                        boolean addFlag = true;
                        for (EduLivePlaceVO livePlaceVO : livePlaceVOList) {
                            if (eduLivePlaceOffline.getSfzh().equals(livePlaceVO.getSfzh())) {
                                addFlag = false;
                            }
                        }
                        if (addFlag) {
                            EduLivePlaceVO placeVO = Convert.convert(EduLivePlaceVO.class, eduLivePlaceOffline);
                            placeVO.setAuthStatusName("审核不通过");
                            livePlaceVOList.add(placeVO);
                        }
                    }
                }
            }
            cache.put(key,livePlaceVOList);
            return livePlaceVOList;
        }else{
            if (!CollectionUtils.isEmpty(offlineList)){
                List<EduLivePlaceVO> livePlaceVOList = new ArrayList<>();
                for (EduLivePlaceOffline eduLivePlaceOffline:offlineList){
                    if (AuthStatusEnum.NODO.getType().equals(eduLivePlaceOffline.getAuthStatus())){
                        boolean addFlag=true;
                        for (EduLivePlaceVO livePlaceVO : livePlaceVOList) {
                            if (eduLivePlaceOffline.getSfzh().equals(livePlaceVO.getSfzh())) {
                                addFlag=false;
                                if (AuthStatusEnum.NO.getType().equals(livePlaceVO.getAuthStatus())){
                                    livePlaceVO.setAuthStatusName("审核中");
                                    livePlaceVO.setAuthStatus(AuthStatusEnum.NODO.getType());
                                }
                            }
                        }
                        if (addFlag) {
                            EduLivePlaceVO placeVO = Convert.convert(EduLivePlaceVO.class, eduLivePlaceOffline);
                            placeVO.setAuthStatusName("待审核");

                            livePlaceVOList.add(placeVO);
                        }
                    }else {
                        boolean addFlag=true;
                        for (EduLivePlaceVO livePlaceVO : livePlaceVOList) {
                            if (eduLivePlaceOffline.getSfzh().equals(livePlaceVO.getSfzh())) {
                                addFlag=false;
                            }
                        }
                        if (addFlag) {
                            EduLivePlaceVO placeVO = Convert.convert(EduLivePlaceVO.class, eduLivePlaceOffline);
                            placeVO.setAuthStatusName("审核不通过");
                            livePlaceVOList.add(placeVO);
                        }
                    }
                }
                cache.put(key,livePlaceVOList);
                return livePlaceVOList;
            }
        }
        cache.put(key,new ArrayList<>());
        return new ArrayList<>();
    }
}
